<template>
  <div class="plan-filing bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">预案修订记录</h2>


    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">

      <QueryForm :model="search" :formItems="formItems" @search="searchPlans" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">

      <!-- <el-button @click="openImportDialog">导入</el-button> -->
      <el-button @click="exportData(planData, '预案修订记录', selectedIds)">导出</el-button>
    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedPlanData" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_ID" label="预案编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PARK_CODE" label="园区编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="COMPANY_CODE" label="企业编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="AREA_CODE" label="行政区划" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_NAME" label="预案名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_TYPE" label="预案类别" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_LEVEL" label="预案等级" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PREPARATION_DEPARTMENT" label="编制单位" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="PLAN_FILE" label="修订应急预案文件" header-align="center" align="center">
          <template #default="scope">
            <div>{{ scope.row.EMERGENCE_PLAN_LEVEL }}</div>
            <el-button style="width: 75px; height: 30px;"
              @click="uploadfile(apiBaseUrl + '/download/' + scope.row.EMERGENCE_PLAN_LEVEL)">
              下载查看
            </el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="REVISE_STATE" label="修订状态" header-align="center" align="center"></el-table-column> -->
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openImportDialog(scope.row)" link>修订</el-button>
            <el-button type="danger" size="small" @click="deleteSelected(scope.row)" link>移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->

    <Pagination v-if="planData.length" :tableData="planData" @alltabledata="alltabledata" />
    <!--  -->

    <!--  -->
    <el-dialog width="400px" class="dialog-from" v-model="isImportDialogOpen" title="导入" destroy-on-close align-center
      :before-close="closeImportDialog">
      <div class="mb-4">
        <label for="importFile" class="block text-sm font-medium">选择文件</label>
        <input type="file" id="importFile" @change="handleFileUpload" accept=".csv, .xlsx" class="mt-1 block w-full">
      </div>
      <div class="mt-4 flex justify-end space-x-2">
        <el-button @click="closeImportDialog"
          class="bg-secondary text-secondary-foreground px-4 py-2 rounded">取消</el-button>
        <el-button v-loading.fullscreen.lock="fullscreenLoading" @click="confirmImport"
          class="bg-accent text-accent-foreground px-4 py-2 rounded" type="primary">确认导入</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import axios from 'axios'

import { dayjs, ElLoading } from "element-plus"
const { proxy } = getCurrentInstance()
import { exportData, uploadfile } from '#/utils/exportfile.js'
const apiBaseUrl = ref(proxy.$currentUrl + '/api/plan-entry')
// 搜索相关
const search = ref({
  EMERGENCE_PLAN_ID: "",
  EMERGENCE_PLAN_NAME: '',

})
const formItems = ref([
  {
    label: '预案编码：:',
    model: 'EMERGENCE_PLAN_ID',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '预案名称：',
    model: 'EMERGENCE_PLAN_NAME',
    type: 'input',
    // placeholder: '请选择',
    // options: [
    //   { label: '自然灾害', value: '自然灾害' },
    //   { label: '事故灾难', value: '事故灾难' },
    //   { label: '公共卫生时间', value: '公共卫生时间' },
    //   { label: '社会安全事件', value: '社会安全事件' },
    //   { label: '其他突发事件', value: '其他突发事件' },
    // ],
  },


])
const rowKey = (row) => row.ID
const loading = ref(false)
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
// 数据相关

const planData = ref([])
const isViewDialogOpen = ref(false)
const selectedItem = ref(null)
const selectedIds = ref([])
const displayedPlanData = ref([])
const filesdata = []
const isImportDialogOpen = ref(false)
const fullscreenLoading = ref(false)
// 打开导入对话框
const openImportDialog = (item) => {
  if (item.selected != undefined) {
    selectedItem.value = { ...item }
  }
  isImportDialogOpen.value = true
}

// 关闭导入对话框
const closeImportDialog = () => {
  isImportDialogOpen.value = false
  selectedItem.value = {}
}

// 文件上传处理
const handleFileUpload = (event) => {
  filesdata[0] = event.target.files[0]
}

const confirmImport = async () => {
  // 实现导入逻辑
  let formData = new FormData()

  if (Object.keys(selectedItem.value) != 0) {
    formData.append('ID', selectedItem.value.ID)
    formData.append('file', filesdata[0])
    await axios.put(`${apiBaseUrl.value}/${selectedItem.value.ID}/revise`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    alert('修订成功')
    closeImportDialog()
    searchPlans()
  } else {
    formData.append('file', filesdata[0])
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    try {
      const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      loading.close()
      alert('导入成功')
      closeImportDialog()
      searchPlans()
    } catch (error) {
      loading.close()
      console.error('导入失败:', error)
      alert('导入失败: ' + (error.response?.data?.message || error.message))
    }
  }

}
const alltabledata = (data) => {
  displayedPlanData.value = data

}
const deleteSelected = async (row) => {

  try {
    if (confirm('是否移除')) {
      await axios.delete(`${apiBaseUrl.value}/${row.ID}`)
      alert('移除成功')
      await searchPlans()
    }
  } catch (error) {
    console.error('移除记录失败:', error)
    alert('移除记录失败: ' + (error.response?.data?.message || error.message))
  }
}
// API 调用函数
const searchPlans = async () => {
  displayedPlanData.value = []
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    planData.value = response.data.map(app => ({ ...app, selected: false }))
    selectedIds.value = []
  } catch (error) {
    console.error('搜索记录失败:', error)
    alert('搜索记录失败')
  }
}
// 事件处理函数
const resetSearch = () => {
  search.value = {
    EMERGENCE_PLAN_ID: '',
    EMERGENCE_PLAN_TYPE: '',
    EMERGENCE_PLAN_LEVEL: '',
    EMERGENCE_PLAN_NAME: '',
  }
  searchPlans()
}
// 生命周期钩子
onMounted(() => {
  searchPlans()
})

</script>

<style scoped>
/* 移除所有现有的样式 */
</style>
